import 'whatwg-fetch'; // 兼容FF,SAFARI,CHROME浏览器的polyfill
import 'fetch-detector'; // 针对IE老版本浏览器的兼容
import 'fetch-ie8'; // 针对IE老版本浏览器的兼容
import fetchJsonp from 'fetch-jsonp'; // 兼容老接口的无奈
import qs from 'querystring';
import domainName from './domain-config';
import { webviewRedirect, isWXSQ } from '@/common/utils';
import { DOMModal } from '@/components/DOMModal';
import Toast from '@/components/Toast';
require('es6-promise/auto');

const {
  NODE_ENV,
  REACT_APP_ISM,
  REACT_APP_PREHOST,
  REACT_APP_APITYPE
} = process.env;
const isM = REACT_APP_ISM === 'true';
const PreHost = REACT_APP_PREHOST || '';
const isPre = REACT_APP_APITYPE === 'pre' && PreHost !== '';
const isDynamic = REACT_APP_APITYPE === 'dynamic';

const HOST =
  domainName[NODE_ENV][isPre ? 'pre' : isDynamic ? 'dynamice' : 'default'];
console.log('HOST=>' + HOST, 'REACT_APP_APITYPE=>' + REACT_APP_APITYPE);

/**
 * api 传入参数
 */
interface IOptions {
  param?: any; // 传参
  isNeedAllData?: boolean; // 是否需要返回所有参数
  merges?: any; // 合并fetch请求参数
  isPlat?: boolean; // 是否是第三方接口
}

/**
 * content-type
 */
const CONTENT_TYPES = {
  post: 'application/json',
  postUpload: 'multipart/form-data',
  postForm: 'application/x-www-form-urlencoded'
};

function handleResponse(res: any, isNeedAllData: boolean) {
  const { code, data, msg } = res;
  switch (code) {
    case 200:
      return isNeedAllData ? res : data;
    case 300:
      if (isM) {
        const LOGIN_URL = isWXSQ()
          ? `https://wq.jd.com/pinbind/pintokenredirect?scope=1&biz=${process
              .env.REACT_APP_BIZ || 'activitycollector'}&url=`
          : `//plogin.m.jd.com/user/login.action?appid=${process.env
              .REACT_APP_APPID || 773}&returnurl=`;
        window.location.href =
          LOGIN_URL + encodeURIComponent(window.location.href);
      } else {
        window.location.href =
          'https://passport.jd.com/uc/login?ReturnUrl=' +
          encodeURIComponent(window.location.href);
      }
      break;
    /** 11001-12000 为短信验证码错误码 **/
    case 500:
      Toast.show(msg || '操作失败');
      break;
    case 11000: // 请求参数不合规
      Toast.show(msg || '请求参数不合规');
      break;
    case 11001:
    case 11002:
    case 11003:
    case 11004:
    case 11005:
    case 11006:
    case 11007:
    case 11008:
    case 11009:
      Toast.show(msg || '系统繁忙请稍后重试');
      break;
    default:
      DOMModal.handleOpenModal({
        content: msg || '系统繁忙请稍后重试',
        errorCode: code
      });
      break;
  }
}

function fetchFun(url: string, method: string, options: IOptions = {}) {
  let { merges, isNeedAllData } = options;
  const ResponseFunc = new Promise(resolve => {
    if (method === 'jsonp') {
      resolve(fetchJsonp(url));
    } else {
      resolve(
        fetch(url, {
          method: method === 'get' ? 'GET' : 'POST',
          mode: 'cors',
          credentials:
            HOST.indexOf('127.0.0.1') !== -1 || HOST.indexOf('localhost') !== -1
              ? 'same-origin'
              : 'include',
          ...merges
        })
      );
    }
  });

  return new Promise(resolve => {
    ResponseFunc.then((res: any) => {
      if (res.status >= 400) {
        webviewRedirect(
          isM
            ? `${window.location.origin}/error${window.location.search}`
            : `https://www.jd.com/error2.aspx`
        );
        return null;
      }
      return res.json();
    })
      .then(user => {
        resolve(handleResponse(user, isNeedAllData || false));
      })
      .catch(err => {
        console.error(err);
      });
  });
}

/**
 * 处理get url
 */
function get(url: string, method: string, options: IOptions = {}) {
  options.param = {
    ...options.param,
    t: Math.floor(Math.random() * 10000)
  };
  url += (url.indexOf('?') === -1 ? '?' : '&') + qs.stringify(options.param);
  return fetchFun(url, method, options);
}

/**
 * 处理post
 * content-type可定制
 */
function post(url: string, method: string, options: IOptions = {}) {
  const { param } = options;
  options.merges = {
    headers: { 'Content-Type': CONTENT_TYPES[method || 'post'] },
    body: method === 'postForm' ? qs.stringify(param) : JSON.stringify(param)
  };
  if (param instanceof FormData) {
    delete options.merges.headers;
    options.merges.body = param;
  }
  return fetchFun(url, method, options);
}

/**
 * ajax入口
 */
function ajax(url: string, method: string, options: IOptions = {}) {
  if (method.indexOf('post') > -1) {
    return post(url, method, options);
  } else {
    return get(url, method, options);
  }
}

class Api {
  static Request(method: string, url: string, options: IOptions = {}) {
    console.log(method, url, options);
    const { param, isPlat } = options;
    // formdata格式不拼公共参数
    if (!(param instanceof FormData)) {
      options.param = {
        ...param
      };
    }
    return ajax(isPlat ? url : HOST + url, method, options);
  }
}

export default Api;
